using ColorFillGame.Domain.Entities;
using ColorFillGame.Domain.Repositories;
using ColorFillGame.Infrastructure.Data;
using Microsoft.EntityFrameworkCore;

namespace ColorFillGame.Infrastructure.Repositories;

public class PlayerRepository : IPlayerRepository
{
    private readonly AppDbContext _context;

    public PlayerRepository(AppDbContext context)
    {
        _context = context;
    }

    public async Task<Player?> GetByIdAsync(Guid id)
    {
        return await _context.Players.FindAsync(id);
    }

    public async Task<Player?> GetByConnectionIdAsync(string connectionId)
    {
        return await _context.Players.FirstOrDefaultAsync(p => p.ConnectionId == connectionId);
    }

    public async Task<IEnumerable<Player>> GetByGameIdAsync(Guid gameId)
    {
        // 返回属于指定游戏的所有玩家
        return await _context.Players.Where(player => player.GameId == gameId).ToListAsync();
    }

    public async Task AddAsync(Player player)
    {
        await _context.Players.AddAsync(player);
    }

    public Task UpdateAsync(Player player)
    {
        _context.Players.Update(player);
        return Task.CompletedTask;
    }

    public async Task DeleteAsync(Guid id)
    {
        var player = await GetByIdAsync(id);
        if (player != null)
        {
            _context.Players.Remove(player);
        }
    }

    public async Task SaveChangesAsync()
    {
        await _context.SaveChangesAsync();
    }
}